package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.auth.client.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.FindPswDto;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.VerifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class VerifyServiceImpl implements VerifyService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    CheckCodeClient client;
    @Autowired
    XcUserMapper xcUserMapper;

    @Override
    public void findPassword(FindPswDto findPswDto) {
        //1.进行校验
        String email = findPswDto.getEmail();
        String checkcode = findPswDto.getCheckcode();

        //2.对验证码进行检验
        Boolean verify = client.verify(email, checkcode);
        if (!verify){
            throw new RuntimeException("验证码错误");
        }

        //3.输入两次密码校验
        String password = findPswDto.getPassword();
        String confirmpwd = findPswDto.getConfirmpwd();
        if (!password.equals(confirmpwd)){
            throw new RuntimeException("验证码错误");
        }

        //4.检测用户是否存在
        LambdaQueryWrapper<XcUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(XcUser::getEmail,findPswDto.getEmail());
        XcUser xcUser = xcUserMapper.selectOne(lambdaQueryWrapper);
        if (xcUser==null){
            throw new RuntimeException("用户不存在");
        }

        //5.保存密码
        xcUser.setPassword(new BCryptPasswordEncoder().encode(password));
        xcUserMapper.updateById(xcUser);
    }
}
